package com.xyy.controller;

import com.xyy.common.PageResult;
import com.xyy.common.Result;
import com.xyy.entity.User;
import com.xyy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/user-manage")
@Validated
public class UserManageController {

    @Autowired
    private UserService userService;

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<Void> updateUser(@Valid @RequestBody User user) {
        try {
            userService.updateUser(user);
            return Result.success();
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 软删除用户
     */
    @DeleteMapping("/delete/{userId}")
    public Result<Void> deleteUser(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            userService.deleteUser(userId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量软删除用户
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteUser(@RequestBody @NotEmpty(message = "用户ID列表不能为空") List<Long> userIds) {
        try {
            userService.batchDeleteUser(userIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询用户
     */
    @PostMapping("/page")
    public Result<PageResult<User>> pageQueryUsers(@RequestBody(required = false) User user,
                                                  @RequestParam(defaultValue = "1") Integer current,
                                                  @RequestParam(defaultValue = "10") Integer size) {
        try {
            if (user == null) {
                user = new User();
                }
                
            // 验证分页参数
            if (current == null || current < 1) current = 1;
            if (size == null || size < 1) size = 10;
            
            PageResult<User> result = userService.pageQueryUsers(user, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询用户详情
     */
    @GetMapping("/detail/{userId}")
    public Result<User> getUserById(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            User user = userService.getUserById(userId);
            return Result.success(user);
        } catch (Exception e) {
            log.error("查询用户详情失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/toggle-status/{userId}")
    public Result<Void> toggleUserStatus(@PathVariable @NotNull(message = "用户ID不能为空") Long userId,
                                        @RequestParam @NotNull(message = "状态不能为空") Integer status) {
        try {
            userService.toggleUserStatus(userId, status);
            return Result.success();
        } catch (Exception e) {
            log.error("切换用户状态失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户列表（不分页）
     */
    @GetMapping("/list")
    public Result<List<User>> getUserList() {
        try {
            List<User> users = userService.list();
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询已删除的用户
     */
    @GetMapping("/deleted-users")
    public Result<PageResult<User>> getDeletedUsersPage(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer current,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页大小必须大于0") Integer size) {
        try {
            PageResult<User> result = userService.getDeletedUsersPage(current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询已删除用户失败", e);
            return Result.error("查询已删除用户失败: " + e.getMessage());
        }
    }



    /**
     * 恢复软删除的用户
     */
    @PutMapping("/restore/{userId}")
    public Result<Void> restoreUser(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            userService.restoreUser(userId);
            return Result.success();
        } catch (Exception e) {
            log.error("恢复用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量恢复软删除的用户
     */
    @PutMapping("/batch-restore")
    public Result<Void> batchRestoreUsers(@RequestBody @NotNull(message = "用户ID列表不能为空") List<Long> userIds) {
        try {
            userService.batchRestoreUsers(userIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量恢复用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户查看个人信息
     */
    @GetMapping("/profile")
    public Result<User> getUserProfile(@RequestParam @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户个人信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户更新个人信息
     */
    @PutMapping("/profile/update")
    public Result<Void> updateUserProfile(@Valid @RequestBody User user) {
        try {
            // 只允许更新部分字段，防止恶意修改
            User existingUser = userService.getUserById(user.getId());
            if (existingUser == null) {
                return Result.error("用户不存在");
            }
            
            // 只更新允许的字段
            existingUser.setNickname(user.getNickname());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            existingUser.setGender(user.getGender());
            existingUser.setBirthDate(user.getBirthDate());
            existingUser.setAddress(user.getAddress());
            
            userService.updateUser(existingUser);
            return Result.success();
        } catch (Exception e) {
            log.error("更新用户个人信息失败", e);
            return Result.error(e.getMessage());
        }
    }

} 